package com.onekbase.demo.thead;

import java.util.Timer;
import java.util.TimerTask;

public class InterruptDemo {

    public static void main(String[] args) {
        InterruptExampleThread thread = new InterruptExampleThread("MyThread");
        thread.start();
        // 10秒后中断线程
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                thread.interrupt();
            }
        }, 10000);
    }

    static class InterruptExampleThread extends Thread {
        public InterruptExampleThread(String name) {
            super(name);
        }

        @Override
        public void run() {
            while (!Thread.currentThread().isInterrupted()) {
                System.out.println(getName() + " is running...");
                try {
                    // 让线程睡眠一段时间，模拟正在执行的任务
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // 如果线程被中断，将抛出InterruptedException，并设置中断状态
                    System.out.println(getName() + " was interrupted, trying to finish what we were doing...");
                    // 如果我们想要立即停止线程，我们可以再次设置中断状态
                    // 外部interrupt会引起中断异常，但状态可能会被刷为非中断
                     Thread.currentThread().interrupt();
                }
            }
            System.out.println(getName() + " was interrupted, finishing task...");
        }
    }
}
